package org.ainlolcat.ainscience.UI;

import org.ainlolcat.ainscience.Controller;
import org.ainlolcat.ainscience.entity.Entity;
import org.ainlolcat.ainscience.entity.links.Link;
import org.ainlolcat.ainscience.matrix.MatrixFile;
import org.ainlolcat.ainscience.matrix.MatrixFileParser;
import org.ainlolcat.ainscience.project.Project;
import org.ainlolcat.ainscience.templates.Template;
import org.ainlolcat.ainscience.tools;
import org.jdom.Element;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: ain
 * Date: 11/17/11
 * Time: 1:55 AM
 * To change this template use File | Settings | File Templates.
 */
public class EntityCreator extends JFrame implements XListPane.SelectedValueListener{
    private String title;
    private int screen = 0;
    private String filename;
    private String templateName;
    private String entityType;
    private String name;

    private String matrixNum;

    private String currentLink;
    private List<Link> links;
    List<Element> elLinks;
    Hashtable<String, String> resolvedLinks;


    JTextField input_field;
    XListPane xlist = null;
    JLabel label = null;

    public EntityCreator(String name){
        super(name);
        title = name;
        init();
    }

    public  void init(){
        this.setSize(tools.getScreenSize().width/2,tools.getScreenSize().height/2);
        this.setLayout(new FlowLayout(FlowLayout.LEFT));
        showSelectFileScreen();
    }


    //select entity file
    JButton openProject = null;
    private void showSelectFileScreen(){
        setTitle(title+": Select entity file");
        openProject = new JButton("Open");
        openProject.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                JFileChooser fc = new JFileChooser();
                fc.showOpenDialog(null);
                File file = fc.getSelectedFile();
                try {
                    filename = file.getCanonicalPath();
                    showSelectTemplateScreen();
                } catch (IOException e1) {
                    e1.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                    JOptionPane.showMessageDialog(null,"Sorry. Error occurred while getData filename: "+e1.getLocalizedMessage());
                }
            }
        });
        this.add(openProject);
        this.setVisible(true);
    }
    private void clearSelectFileScreen(){
        this.remove(openProject);
        openProject = null;
    }

    //select template

    private void showSelectTemplateScreen(){
        clearSelectFileScreen();
        setTitle(title+": Select template");
        xlist = new XListPane(Controller.getInstance().getProject().getTemplateNames());
        xlist.addSelectedValueListener(this);
        screen = 2;
        this.getContentPane().add(xlist);
        this.setVisible(true);
    }
    private void clearSelectTemplateScreen(){
        this.remove(xlist);
        this.repaint();
        xlist = null;
    }

    //select type
    private void showSelectTypeScreen(){
        clearSelectTemplateScreen();
        setTitle(title + ": Select type");
        Template temp = Controller.getInstance().getProject().getTemplateByName(templateName);
        List<String> types = temp.getEntityTypes();
        xlist = new XListPane(types);
        xlist.addSelectedValueListener(this);
        add(xlist);
        this.setVisible(true);
        screen = 3;
    }
    private void clearSelectTypeScreen(){
        this.remove(xlist);
        this.repaint();
        xlist = null;
    }

    //prepare for screen5
    //<link name="sensevity" column="0" l2template="sensevity" l2entityType="ava" linkType="equal"/>
    private void findLinks4ThisType(){
        clearSelectTypeScreen();
        Template temp = Controller.getInstance().getProject().getTemplateByName(templateName);
        Element descr = temp.getEntityParseParams(entityType);
        Element elinks = descr.getChild("links");
        if (elinks!=null){
            List<String> names = new ArrayList<String>();
            elLinks = elinks.getChildren("link");
            for (Element link:elLinks){
                names.add(link.getAttributeValue("name"));
            }
            resolvedLinks = new Hashtable<String, String>();
        }
        showResolveLinkScreen();
    }


    //<link name="sensevity" column="0" l2template="sensevity" l2entityType="ava" linkType="equal"/>
    private void showResolveLinkScreen(){
        clearResolveLinkScreen();
        setTitle(title + ": Resolve links");
        if (elLinks!=null){
            if (elLinks.size()==resolvedLinks.size()){
                showSelectMatrixNumScreen();
            }
            for (Element link:elLinks){
                if (!resolvedLinks.containsKey(link.getAttributeValue("name"))){
                    //getData link name
                    currentLink = link.getAttributeValue("name");
                    label = new JLabel("Link: "+currentLink);
                    this.add(label);
                    //getData names for entity which can be used
                    List<Entity> names = Controller.getInstance()
                            .getProject().
                                    getEntitiesByType(link.getAttributeValue("l2entityType"));
                    //translate entity list to name list
                    List<String> nameList = new ArrayList<String>();
                    for (Entity ent:names){
                        nameList.add(ent.getName());
                    }
                    //create list
                    xlist = new XListPane(nameList);
                    xlist.addSelectedValueListener(this);
                    this.add(xlist);
                    break;
                }
            }
        }else {
            showSelectMatrixNumScreen();
        }
        screen = 5;
        this.setVisible(true);
    }
    private void clearResolveLinkScreen(){
        if (xlist !=null){
            this.remove(xlist);
            xlist = null;
        }
        if (label !=null){
            this.remove(label);
            label = null;
        }
        this.repaint();
    }

    JButton next_button;
    private void showSelectMatrixNumScreen(){
        clearResolveLinkScreen();
        setTitle(title+": Set matrix num");
        try {
            MatrixFile mf = new MatrixFileParser().parseFile(
                    Controller.getInstance().getProject().getTemplateByName(templateName).getMatrixParserParams(),
                    filename);
            int size = mf.size();
            setTitle(title+": Set matrix num from : "+size);
        } catch (IOException e1) {
            JOptionPane.showMessageDialog(null,"Sorry, error occurred: "+e1.getLocalizedMessage());
            e1.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        input_field = new JTextField();
        input_field.setPreferredSize(new Dimension(100,30));
        add(input_field);
        next_button = new JButton("next");
        next_button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                matrixNum = input_field.getText();
                showEntityNameScreen();
            }
        });
        add(next_button);
    }
    private void clearSelectMatrixNumScreen(){
        this.remove(input_field);
        this.remove(next_button);
        input_field =null;
        next_button = null;
        this.repaint();
    }

    private void showEntityNameScreen(){
        clearSelectMatrixNumScreen();
        setTitle(title + ": Write entity name");
        input_field = new JTextField();
        input_field.setPreferredSize(new Dimension(100,30));
        add(input_field);
        JButton button = new JButton("create");
        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                name = input_field.getText();
                String temlateID = Controller.getInstance().getProject().
                        getTemplateByName(templateName).getId().toString();

                Hashtable<String,String> params = new Hashtable<String, String>();
                if (name!=null)          params.put("name",          name);
                if (filename!=null)      params.put("file",          filename);
                if (temlateID!=null)     params.put("templateID",    temlateID);
                if (entityType!=null)    params.put("entityType",    entityType);
                if (matrixNum!=null)     params.put("matrixNum",     matrixNum);

                Entity entity = null;

                JOptionPane.showMessageDialog(null,"NOT IMPLEMENTED");
                /*try {
                    entity = new EntityFactory().parse(params,links);
                } catch (IOException e1) {
                    JOptionPane.showMessageDialog(null,"Sorry, error occurred: "+e1.getLocalizedMessage());
                    e1.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }      */
                Controller.getInstance().addEntity(entity);
            }
        });
        add(button);
        this.setVisible(true);
        this.repaint();
    }

    public void handleSelected(String value) {
        //template selection screen
        if (screen == 2){
            templateName = value;
            showSelectTypeScreen();
        } else if (screen == 3){
            entityType = value;
            findLinks4ThisType();
        } if (screen == 5){
            Project pr = Controller.getInstance().getProject();
            resolvedLinks.put(currentLink,value);
            showResolveLinkScreen();
        }
    }
}
